import json
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.models import User
from django.contrib.auth import login,logout,authenticate
from django.contrib.auth.decorators import login_required, permission_required
from apps.basic.models import MyUser
from django.contrib.auth.models import Group, Permission
from django.urls import reverse
from django.shortcuts import redirect
from datetime import datetime
from django.core import serializers
from django.views.decorators.clickjacking import xframe_options_sameorigin
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from apps.basic.forms import UserRegForm, UserPassWordChangeForm, UserInfoChangeForm

# 用户注册视图，无登录和权限要求，开放注册界面
@xframe_options_sameorigin
def user_reg(request, is_back_login):
    if request.method=="GET":
        form_obj=UserRegForm()
        return render(request,'basic/user_reg.html',{"form_obj":form_obj,"is_login":is_back_login})
    if request.method=="POST":
        form_obj=UserRegForm(request.POST,request.FILES)
        if form_obj.is_valid():
            uname=request.POST.get("username",'')
            users=MyUser.objects.filter(username=uname)
            if users:
                for user in users:
                    user_img=user.user_img
                info='用户已经存在'
            else:
                form_obj.cleaned_data.pop("re_password")           # re_password密码确认在表单中，但是数据库中无该字段，这里删除
                form_obj.cleaned_data["is_staff"]=1
                form_obj.cleaned_data["is_active"]=0               # 默认注册不激活，需要管理员审批
                form_obj.cleaned_data["is_superuser"] = 0          # 非管理员
                # 接收页面传递过来的参数，进行用户新增
                user = MyUser.objects.create_user(**form_obj.cleaned_data)
                user_img = user.user_img
                info = '注册成功,请登陆'
            return render(request, 'basic/user_reg.html', {"form_obj": form_obj, "info": info, "user_img": user_img})
        else:
            errors = form_obj.errors
            print(errors)
            return render(request, "basic/user_reg.html", {'form_obj': form_obj, 'errors': errors})

# 用户登录视图，无登录和权限要求，开放登录界面
def user_login(request):
    return render(request, 'basic/user_login.html')
# 用户退出视图，无登录和权限要求
def user_logout(request):
    logout(request)                     # 清楚登录状态
    return redirect(reverse("lms_login"))

# 用户登录ajax请求，无登录和权限要求，开放登录请求
def ajax_login_data(request):
    uname = request.POST.get("username")
    pwd = request.POST.get("password")
    json_dict = {}
    if uname and pwd:  # 不为空的情况下，查询数据库
        if MyUser.objects.filter(username=uname):  # 判断用户是否存在
            # 如果存在，进行验证
            user = authenticate(username=uname, password=pwd)
            # print(user)
            if user:  # 如果验证通过
                if user.is_active:  # 如果用户状态为激活
                    login(request, user)                # 进行登陆操作，完成session的设置
                    json_dict["code"] = 1000
                    json_dict["msg"] = "登陆成功"
                else:
                    json_dict["code"] = 1001
                    json_dict["msg"] = "用户还未激活"
            else:
                json_dict["code"] = 1002
                json_dict["msg"] = "账号密码不对，请重新输入"
        else:
            json_dict["code"] = 1003
            json_dict["msg"] = "用户账号有误，请查询"
    else:
        json_dict["code"] = 1004
        json_dict["msg"] = "用户名或者密码为空"
    print(json_dict)
    return JsonResponse(json_dict)

# 用户首页视图，需要登录后才可访问
@login_required                 # 用户登录装饰器（登录用户才能访问）
def user_index(request):
    return render(request, 'basic/index.html', {'username': request.user.username})

# 用户信息管理展示
@login_required
@xframe_options_sameorigin
@permission_required('basic.check_myuser')
def user_info_manage(request):
    if request.method == "GET":
        status = request.GET.get("level")
        # truename = request.GET.get("truename", '')
        # status = request.GET.get("status")
        #
        # # search_dict = dict()
        # if level:
        #     search_dict["level"] = level
        # if truename:
        #     search_dict["truename"] = truename
        # if status:
        #     search_dict["status"] = status
        #
        # datas = MyUser.objects.filter(**search_dict).order_by("-id")
        datas = MyUser.objects.all()
        for data in datas:
            data.create_time = data.create_time.date()
        context = {
            'users': datas,
        }
        return render(request, 'basic/user_info_manage.html', context=context)

# 该功能未完成调试--------------------------------------------------------------------------
def ajax_user_info_search(request):
    status_code = request.POST.get("status_code")
    name_search = request.POST.get("name_search")
    print(status_code)
    print(name_search)
    search_dict = dict()
    if status_code:
        search_dict["is_active"] = status_code
    if name_search:
        search_dict["username"] = status_code
    datas = MyUser.objects.filter(**search_dict).order_by("-id")
    print(datas)
    context = {
        'users': datas,
    }
    render(request, 'basic/user_info_manage.html', context=context)
    json_dict = {"code": "1000"}
    return JsonResponse(json_dict)


# 用户状态审批
@login_required
def ajax_user_approval(request):
    uid = request.POST.get("user_id")
    active = MyUser.objects.filter(id=uid).values('is_active')
    if active[0]['is_active'] == 0:
        MyUser.objects.filter(id=uid).update(is_active=1)
    else:
        MyUser.objects.filter(id=uid).update(is_active=0)
    json_dict = {"code": "1000"}
    return JsonResponse(json_dict)

# 用户组管理页面视图
@login_required
@xframe_options_sameorigin
@permission_required('auth.view_group')
def user_group_manage(request):
    if request.method == "GET":
        datas = Group.objects.all()
        context = {
            'group_data': datas,
        }
        return render(request, 'basic/user_group_manage.html', context=context)

# 用户组管理页面新增数据模态反馈数据保存视图
@login_required
@xframe_options_sameorigin
@permission_required('auth.add_group')
def user_group_add(request):
    gName = request.POST.get("groupName")
    d = dict(name=gName)
    Group.objects.create(**d)
    json_dict = {"code": "1000"}
    return JsonResponse(json_dict)

# 用户组管理页面修改数据模态反馈数据保存视图
@login_required
@xframe_options_sameorigin
@permission_required('auth.change_group')
def user_group_change(request):
    g_id = request.POST.get("groupId")
    g_name = request.POST.get("groupName")
    Group.objects.filter(id=g_id).update(name=g_name)
    json_dict = {"code": "1000"}
    return JsonResponse(json_dict)

# 用户组管理页面删除数据模态反馈数据保存视图
@login_required
@xframe_options_sameorigin
@permission_required('auth.delete_group')
def user_group_delete(request):
    g_id = request.POST.get("groupId")
    oneGroupData = Group.objects.get(id=g_id)
    oneGroupData.delete()
    json_dict = {"code": "1000"}
    return JsonResponse(json_dict)

# 用户组管理权限配置页面响应视图
@login_required
@xframe_options_sameorigin
@permission_required('auth.add_permission')
def group_permissions_manage(request):
    if request.method == "GET":
        user_group = Group.objects.all()
        permission_all = Permission.objects.all()  # 所有可配置的权限数据列表
        context = {
            'group_data': user_group,              # 初始化界面把所有用户组信息初始化到下拉选项
            'permission_all': permission_all,      # 初始化界面的时候把所有权限传递过去显示
        }
        return render(request, 'basic/group_permissions_manage.html', context=context)

# 操作用户组选项，对应同步改变权限框中的权限为当前配置权限
@login_required
def ajax_init_group_permissions(request):
    g_id = request.POST.get("groupId")            # 获取当前需要配置权限的用户组ID
    if int(g_id) <= 0:
        return JsonResponse("", safe=False)
    group_current = Group.objects.get(id=g_id)
    group_permissions_current = group_current.permissions.all()    # 当前用户组的权限
    group_per_selected = []
    for per in group_permissions_current:
        group_per_selected.append(per.id)
    return JsonResponse(group_per_selected, safe=False)            # 当前用户组的权限id全部输出前端
# 保存用户配置的权限信息
@login_required
@permission_required('auth.add_permission')
def ajax_group_permissions_save(request):
    g_id = request.POST.get("groupId")                          # 获取当前需要配置权限的用户组ID
    g_permissionsId = request.POST.get("permissionsId")            # 获取当前需要配置权限的用户组ID
    g_permissionsId_list = json.loads(g_permissionsId)
    group = Group.objects.get(id=g_id)
    group.permissions.clear()                    # 清空当前配置的权限
    for ID in g_permissionsId_list:
        permission = Permission.objects.get(id=int(ID))     # 获取待添加的权限
        group.permissions.add(permission)              # 添加用户组的权限
    json_dict = {"code": "1000"}
    return JsonResponse(json_dict)

@login_required
@xframe_options_sameorigin
@permission_required('basic.check_myuser')
def user_group_assignment(request):
    if request.method == "GET":
        datas = MyUser.objects.all()
        groups = Group.objects.all()
        user_groups_names = {}
        user_groups_lists_dict = {}
        for user in datas:
            user_groups = user.groups.all()     # 轮训获取用户的归属组
            group_names = ''                    # 保存该用户归属组的名称
            for g in user_groups:
                if g is not None:
                    group_names = group_names + g.name + '/'
            user_groups_names[user.id] = group_names        # 字典保存每个用户的用户ID和用户组名称的字符串，用于显示table中
            user_groups_lists_dict[user.id] = user_groups
        context = {
            'groups': groups,                           # 所有用户组，用户初始化新增用户组时选择用户组的下拉框
            'users': datas,                             # 所有用户信息，用于初始化配置table表格，显示需要配置的用户列表
            'user_groups_names': user_groups_names,     # 字典保存每个用户归属的用户组的字符串，显示在配置table表格中
        }
        return render(request, 'basic/user_group_assignment.html', context=context)

@login_required
@permission_required('basic.check_myuser')
def ajax_add_group_to_user(request):
    u_id = request.POST.get("userId")             # 当前配置用户ID
    g_id = request.POST.get("groupId")            # 当前添加组的ID
    user = MyUser.objects.get(id=u_id)
    group = Group.objects.get(id=g_id)
    user.groups.add(group)
    json_dict = {"code": "1000"}
    return JsonResponse(json_dict)

@login_required
@permission_required('basic.check_myuser')
def ajax_delete_group_to_user(request):
    u_id = request.POST.get("userId")             # 当前配置用户ID
    g_id = request.POST.get("groupId")            # 当前删除组的ID
    json_dict = {}
    user = MyUser.objects.get(id=u_id)
    group = Group.objects.get(id=g_id)
    user_group = user.groups.all()
    if group not in user_group:
        json_dict["code"] = 1001
    else:
        user.groups.remove(group)
        json_dict["code"] = 1000
    return JsonResponse(json_dict)

# 修改密码
@login_required
@xframe_options_sameorigin
def user_password_change(request):
    if request.method == "GET":
        form_obj = UserPassWordChangeForm()
        return render(request,'basic/password_change.html',{"form_obj": form_obj})
    if request.method =="POST":
        form_obj = UserPassWordChangeForm(request.POST, request.FILES)
        if form_obj.is_valid():
            old_passwd = request.POST.get("old_password",'')
            new_passwd = request.POST.get("new_password",'')
            username = request.user.username
            user = authenticate(username=username, password=old_passwd)
            if user is not None and user.is_active:     # 如果验证通过
                user.set_password(new_passwd)
                user.save()
                info = '密码修改成功！'
            else:
                info = '原始密码错误！'
            return render(request,'basic/password_change.html',{"form_obj":form_obj, "info":info})
        else:
            errors = form_obj.errors
            return render(request, "basic/password_change.html", {'form_obj': form_obj, 'errors': errors})

# 修改我的用户信息
@login_required
@xframe_options_sameorigin
def user_info_change(request):
    if request.method == "GET":
        form_obj = UserInfoChangeForm()        # 我的信息表单
        user = request.user
        form_obj["true_name"].initial = user.true_name
        form_obj["email"].initial = user.email
        form_obj["sex"].initial = user.sex
        form_obj["mobile"].initial = user.mobile
        if user.user_img == "":
            user_img_t = "default_user_img.png"       # 未设置头像，使用默认头像
        else:
            user_img_t = user.user_img
        return render(request, 'basic/my_info_change.html', {"form_obj": form_obj, "user_img_t": user_img_t})
    if request.method == "POST":
        form_obj = UserInfoChangeForm(request.POST, request.FILES)
        if form_obj.is_valid():
            user = MyUser.objects.get(username=request.user.username)
            email_t = form_obj.cleaned_data.get("email")
            true_name_t = form_obj.cleaned_data.get("true_name")
            mobile_t = form_obj.cleaned_data.get("mobile")
            sex_t = form_obj.cleaned_data.get("sex")
            user_img_t = form_obj.cleaned_data.get("user_img")
            user.email = email_t
            user.true_name = true_name_t
            user.sex = sex_t
            user.mobile = mobile_t
            user.user_img = user_img_t
            user.update_time = datetime.now()
            user.save()
            user_img = user.user_img
            info = '修改成功'
            print(user_img)
            return render(request, 'basic/my_info_change.html', {"form_obj": form_obj, "info": info,"user_img": user_img})
        else:
            errors = form_obj.errors
            print(errors)
            return render(request, "basic/my_info_change.html", {'form_obj': form_obj, 'errors': errors})
